import { _decorator, instantiate, Prefab, Sprite, tween, Vec3 } from 'cc';
import PlantBase from './PlantBase';

const { ccclass, property } = _decorator;

@ccclass('SunFlower')
export class SunFlower extends PlantBase {
  @property(Prefab)
  sunPrefab: Prefab = null!;

  @property
  sunInterval: number = 1;

  @property
  sunDropRedius: number = 50;

  protected onLoad(): void {
    this.init('sunflower', this.getComponent(Sprite));
    this.schedule(this.produceSun, this.sunInterval);
  }


  produceSun() {
    if (!this.sunPrefab) return;
    const sun = instantiate(this.sunPrefab);
    sun.setParent(this.node.parent);

    // 向日葵头部位置
    const startPos = this.node.position.clone();
    startPos.y + 50; // 偏移到头部上访
    sun.setPosition(startPos);

    // 目标位置
    const endPos = this.node.position.clone();
    endPos.x += (Math.random() - 0.5) * 2 * this.sunDropRedius;
    endPos.y -= 20;

    // 控制点，用贝塞尔曲线
    const controlPos = new Vec3(
      (startPos.x + endPos.x) / 2 + (Math.random() - 0.5) * 50,
      Math.max(startPos.y, endPos.y) + 100,
      0
    );

    tween(sun)
      .to(
        1,
        { position: endPos },
        {
          easing: (t) => {
            const u = 1 - t;
            const p = startPos
              .multiplyScalar(u * u)
              .add(controlPos.multiplyScalar(2 * u * t))
              .add(endPos.multiplyScalar(t * t));
            sun.setPosition(p);
            return t;
          },
        }
      )
      .start();
  }
}
